package com.example.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.UUID;


/**
 * 自定义过滤器工厂，实现添加响应头过滤器
 */
@Slf4j
@Component
public class OnceTokenGatewayFilterFactory  extends AbstractNameValueGatewayFilterFactory {

    @Override
    public GatewayFilter apply(NameValueConfig config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                log.info("====>OnceTokenGatewayFilterFactory 过滤器开始执行");
                String value = config.getValue();
                if ("uuid".equals(value)) {
                    value = UUID.randomUUID().toString();
                } else if ("jwt".equals(value)) {
                    value = JwtGenerator.generateJwt("leifengyang", 1000 * 60 * 60);
                } else {
                    log.warn("token目前只支持uuid和jwt两种类型，默认使用uuid");
                    exchange.getResponse().setStatusCode(HttpStatus.BAD_REQUEST);
                    return exchange.getResponse().setComplete();
                }
                final String token = value;
                Mono<Void> filter = chain.filter(exchange).then(Mono.fromRunnable(() -> {
                    ServerHttpResponse response = exchange.getResponse();
                    HttpHeaders headers = response.getHeaders();
                    headers.add(config.getName(), token);
                    log.info("<====OnceTokenGatewayFilterFactory 过滤器开始执行完成,添加响应头了");
                }));
                log.info("<====OnceTokenGatewayFilterFactory 过滤器执行结束");
                return filter;
            }

        };
    }
}
